package cn.sumpay.servlet;

import cn.sumpay.model.*;

import static cn.sumpay.utils.DataSourceUtil.*;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;

/**
 * Created by Administrator on 2017/1/3.
 */
public class Insert extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        ServletContext servletContext = request.getServletContext();
        Map<String, String[]> parameterMap = request.getParameterMap();
        User user = (User) session.getAttribute("user");
        Integer user_id = user.getUser_id();
        List<AwardsInfo> datalist = (List<AwardsInfo>) servletContext.getAttribute("datalist");
        //核对前台传的数据中票数 和 应投票数 是否一致
        int realSum=0;
        int needSum=0;
        Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
        Iterator<Map.Entry<String, String[]>> iterator = entries.iterator();
        while(iterator.hasNext()){
            realSum+=iterator.next().getValue().length;
        }
        for(AwardsInfo awardsInfo:datalist){
            needSum+=awardsInfo.getAdwards_number();
        }
        if(realSum!=needSum){
            System.out.println("投票数出错了 投票失败");
            request.setAttribute("message",new Message(MessageType.danger,"投票数出错了 投票失败 "+realSum+"/"+needSum));
            request.getRequestDispatcher("/WEB-INF/jsps/message.jsp").forward(request,response);
            return;
        }


        //封装VoteUserMessage VoteDepartMessage
        List<VoteUserMessage> voteuserlist = new ArrayList<VoteUserMessage>();
        List<VoteDepartMessage> votedepartlist = new ArrayList<VoteDepartMessage>();
        for(AwardsInfo awardsInfo : datalist){
            Integer active_id = awardsInfo.getActive_id();
            Integer awards_id = awardsInfo.getAdwards_id();
            if(awardsInfo.getAdwards_type()==1) {
                String[] user_names = parameterMap.get(awardsInfo.getAdwards_name());
                for (String user_name : user_names) {
                    Integer cand_user_id = getUseridByUsername(user_name, awardsInfo.getCand_users());
                    voteuserlist.add(new VoteUserMessage(active_id, awards_id, cand_user_id, user_id));
                }
            }else if(awardsInfo.getAdwards_type()==2){
                String[] depart_names = parameterMap.get(awardsInfo.getAdwards_name());
                for(String depart_name : depart_names) {
                    Integer cand_depart_id = getDepartidByDepartname(depart_name,awardsInfo.getCand_departs());
                    votedepartlist.add(new VoteDepartMessage(active_id, awards_id, cand_depart_id, user_id));
                }
            }
        }
        //获取数据库连接
        Connection connection = getConnection();
        //提交用户投票人员信息
        try {
            connection.setAutoCommit(false);
            String sql1 = "insert into VOTE_USER_MESSAGE values(?,?,?,?)";
            PreparedStatement pst1 = connection.prepareStatement(sql1);
            for(VoteUserMessage voteUserMessage:voteuserlist) {
                pst1.setInt(1, voteUserMessage.getActive_id());
                pst1.setInt(2,voteUserMessage.getAwards_id());
                pst1.setInt(3,voteUserMessage.getCand_user_id());
                pst1.setInt(4,voteUserMessage.getUser_id());
                pst1.addBatch();
            }
            int[] ints1 = pst1.executeBatch();
            //提交部门投票信息
            String sql2 = "insert into VOTE_DEPART_MESSAGE values(?,?,?,?)";
            PreparedStatement pst2 = connection.prepareStatement(sql2);
            for(VoteDepartMessage voteDepartMessage : votedepartlist) {
                pst2.setInt(1, voteDepartMessage.getActive_id());
                pst2.setInt(2,voteDepartMessage.getAwards_id());
                pst2.setInt(3,voteDepartMessage.getCand_depart_id());
                pst2.setInt(4,voteDepartMessage.getUser_id());
                pst2.addBatch();
            }
            int[] ints2 = pst2.executeBatch();
            //核对数据操作数量
            if(ints1.length != voteuserlist.size() || ints2.length!=votedepartlist.size()){
                connection.rollback();
                request.setAttribute("message",new Message(MessageType.danger,"添加至数据库失败"));
                System.out.println("失败");
                request.getRequestDispatcher("/WEB-INF/jsps/message.jsp").forward(request,response);
                return;
            }
            //提交
            connection.commit();
            request.setAttribute("message","投票成功");
            System.out.println("成功");
        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }

        //跳转到message.jsp显示投票成功与否
        request.getRequestDispatcher("/WEB-INF/jsps/message.jsp").forward(request,response);


    }

    private Integer getDepartidByDepartname(String depart_name, List<Depart> cand_departs) {

        for(Depart depart : cand_departs){
            if(depart_name.equals(depart.getDepart_name()))
                return depart.getDepart_id();
        }
        System.out.println("集合中没有部门名对应的部门");
        return -21;
    }

    private Integer getUseridByUsername(String user_name, List<User> cand_users) {

        for(User user : cand_users){
            if(user_name.equals(user.getUser_name())){
                return user.getUser_id();
            }
        }
        System.out.println("集合中没有用户名对应的用户");
        return null;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("insertdoget");

        doPost(request,response);

    }
}
